/**
 * =====================================================================================
 *       @file  ngx_process_cycle.c
 *      @brief  
 *
 *  Detailed description starts here.
 *
 *   @internal
 *     Created  2012年05月08日 20时21分30秒 
 *    Revision  1.0.0.0
 *    Compiler  gcc/g++
 *
 *     @author  luis
 * =====================================================================================
 */

#include <signal.h>
#include <stdlib.h>
#include <string.h>
#include "ngx_config.h"
#include "ngx_event.h"
#include "ngx_conf_file.h"
#include "ngx_process_cycle.h"
#include "ngx_process.h"
#include "constant.h"

extern ngx_module_t *ngx_modules[];
ngx_pid_t       ngx_pid;

static void ngx_worker_process_init(ngx_cycle_t *cycle, ngx_uint_t priority)
{
    ngx_uint_t i;     

    for (i = 0; ngx_modules[i]; i++)
    {
        if (ngx_modules[i]->init_process)
        {
            if (ngx_modules[i]->init_process(cycle) != NGX_OK)
            {
                perror("module init process");
                exit(2);
            }
        }
    }
}

static void ngx_work_process_cycle(ngx_cycle_t *cycle, void *data)
{
    ngx_worker_process_init(cycle, 1); 
    for ( ; ;)
    {
        ngx_process_events_and_timers(cycle);    
    } 
}

static void ngx_start_worker_processes(ngx_cycle_t *cycle, ngx_int_t n)
{
    ngx_int_t i;
    for (i = 0; i < n; i++)
    {
        ngx_spawn_process(ngx_work_process_cycle, cycle, NULL);
    } 
}

void ngx_master_process_cycle(ngx_cycle_t *cycle)
{
    sigset_t set; 

    sigemptyset(&set);
    sigaddset(&set, SIGCHLD);
    sigaddset(&set, SIGALRM);
    sigaddset(&set, SIGIO);
    sigaddset(&set, SIGINT);
    sigaddset(&set, ngx_signal_value(NGX_RECONFIGURE_SIGNAL));
    sigaddset(&set, ngx_signal_value(NGX_REOPEN_SIGNAL));
    sigaddset(&set, ngx_signal_value(NGX_NOACCEPT_SIGNAL));
    sigaddset(&set, ngx_signal_value(NGX_TERMINATE_SIGNAL));
    sigaddset(&set, ngx_signal_value(NGX_SHUTDOWN_SIGNAL));
    sigaddset(&set, ngx_signal_value(NGX_CHANGEBIN_SIGNAL));

    if (sigprocmask(SIG_BLOCK, &set, NULL) == -1)
    {
        perror("block signal failed."); 
        exit(-1); 
    }    

    

    ngx_start_worker_processes(cycle, WORK_PROCESS_NUM); 

    for ( ; ; )
    {
        sleep(1);
    }
}

